<?php

namespace app\index\controller;

use app\common\model\AchievementModel;
use app\common\model\ExcelModel;
use app\common\model\UserModel;
use app\index\controller\IndexBase;
use app\index\model\Page;

/**
 * 
 *  前端成果操作
 * 
 * 时间：2020年4月16日16:23:16
 * 作者：夏立军
 * 
 */
class Achievement extends IndexBase
{

    // 首页
    public function index()
    {
        $uid = session('index_login')->id;

        $achievement = new AchievementModel();
        $achievement_list = $achievement->get_achievement_list_flag_to_2();

        $data = array();
        foreach ($achievement_list as $row) {
            $achievement_classify_table_info = $achievement->get_achievement_classify_table_info_by_cid($row['id']);
            $achievement_classify_table_other_info_count = $achievement->get_achievement_classify_table_other_info_by_tableName_and_uid_count($achievement_classify_table_info['table_name'], $uid);

            $row['achievement_count'] = $achievement_classify_table_other_info_count;
            $data[] = $row;
        }

        return view('index', [
            'achievement_list' => $data,
        ]);
    }

    // 成果详情页
    public function details()
    {
        // 获取分类的ID
        $cid = input('get.cid/d', null);
        if (is_null($cid)) {
            return redirect_index('未传入分类ID', url('User/index'));
        }

        // 实例化一个成果模型
        $achievement = new AchievementModel();

        // 获取中间表的内容
        $classify_table_info = $achievement->get_achievement_classify_table_info_by_cid($cid);

        // 获取已经登录的用户ID
        $uid = session('index_login')->id;
        $classify_table_other_data = $achievement->get_achievement_classify_table_other_info_by_tableName_and_uid($classify_table_info['table_name'], $uid);

        // 数据类型下拉列表数据
        $classify_type_list = config('ams_config.classify_type_list');

        // 获取当前用户的某类成果总数
        $achievement_count = $achievement->get_achievement_classify_table_other_info_by_tableName_and_uid_count($classify_table_info['table_name'], $uid);

        // 读取配置文件的每页数量
        $size = config('ams_config.index_achievement_page_size');

        // 调用每页模型
        $page = new Page();
        $page_res = $page->getPageRes($achievement_count, $size, url('Achievement/details') . '?cid=' . $cid);

        // 分页内容
        $classify_table_other_data = $achievement->get_achievement_classify_table_other_info_page($classify_table_info['table_name'], $uid, $page_res['offset'], $page_res['size']);

        // 获取要编辑的成果名称
        $classify_info = $achievement->get_classify_info_by_id($cid);


        return view('details', [
            'classify_table_info' => $classify_table_info,
            'classify_table_other_data' => $classify_table_other_data,
            'classify_type_list' => $classify_type_list,
            'page_res' => $page_res,
            'uid' => $uid,
            'cid' => $cid,
            'classify_info' => $classify_info,
        ]);
    }

    // 添加一条新纪录
    public function add()
    {
        if (request()->post()) {

            $datas = input('post.data');

            // 数据类型下拉列表数据
            $classify_type_list = config('ams_config.classify_type_list');

            $data = [];
            foreach ($datas as $row) {
                if ($row['value'] == '') {
                    return json(['code' => 1, 'msg' => '数据不能为空']);
                }

                if ('数值' == $classify_type_list[$row['selects'] - 1]['name']) {
                    $data[$row['key']] =  floatval($row['value']) * 100;
                } else if ('时间' == $classify_type_list[$row['selects'] - 1]['name']) {
                    $data[$row['key']] =  strtotime($row['value']);
                } else {
                    $data[$row['key']] = $row['value'];
                }
            }

            $cid = input('post.cid/d', null);
            if (!$cid) {
                return json(['code' => 2, 'msg' => '缺少 cid']);
            }

            $achievement = new AchievementModel();
            $achievement_info = $achievement->get_achievement_classify_table_info_by_cid($cid);
            $data['pid'] = $achievement_info['id'];

            $data['uid'] = session('index_login')->id;
            $data['status'] = 0;
            $data['create_time'] = time();

            $res = $achievement->set_achievement_info_by_data($achievement_info['table_name'], $data);
            if (!$res) {
                return json(['code' => 3, 'msg' => '添加失败']);
            }

            return json(['code' => 0, 'msg' => '添加完成']);
        }

        $cid = input('get.cid/d', null);
        if (is_null($cid)) {
            return redirect_index('未传入分类ID', url('User/index'));
        }

        // 实例化一个成果模型
        $achievement = new AchievementModel();
        // 获取中间表的内容
        $classify_table_info = $achievement->get_achievement_classify_table_info_by_cid($cid);
        // 数据类型下拉列表数据
        $classify_type_list = config('ams_config.classify_type_list');

        return view('add', [
            'cid' => $cid,
            'classify_table_info' => $classify_table_info,
            'classify_type_list' => $classify_type_list,
        ]);
    }

    // 模板下载
    public function download_template()
    {
        $cid = input('post.cid/d', null);
        if (is_null($cid)) {
            return json(['code' => 1, 'msg' => '分类ID丢失，请刷新页面']);
        }

        // 实例化一个成果模型
        $achievement = new AchievementModel();
        // 获取一条分类的数据
        $achievement_info = $achievement->get_classify_info_by_id($cid);

        // 获取 excel 的配置文件
        $excel_template_config =  config('ams_config.excel_template');

        $download_url = $excel_template_config['download_path'] . '/' . $achievement_info['name'] . $excel_template_config['excel_format'];

        if (!is_file(config('ams_config.app_path') . '/public' . $download_url)) {
            return json(['code' => 2, 'msg' => '模板不存在，请联系管理员']);
        }

        return json(['code' => 0, 'msg' => '开始下载', 'url' => $download_url]);
    }

    // 批量上传
    public function upload_template()
    {
        $file = request()->file('achievement_data');
        $file = iconv("utf-8", "gb2312", $file);

        if (empty($file) or !file_exists($file)) {
            return ['code' => 1, 'msg' => '文件不存在!'];
        }

        $excel_model = new ExcelModel();
        $excel = $excel_model->validationExcel($file);
        if (is_null($excel)) {
            return json(['code' => 2, 'msg' => '只能上传excel的文件!']);
        }

        $spreadsheet = $excel->load($file);
        $worksheet = $spreadsheet->getActiveSheet();
        $highestRow = $worksheet->getHighestRow(); // 总行数
        $highestColumn = $worksheet->getHighestColumn(); // 总列数

        $lines = $highestRow - 1;
        if ($lines <= 0) {
            return json(['code' => 3, 'msg' => 'Excel表格中没有数据!']);
        }

        // 获取 cid
        $cid = input('post.cid/d', null);
        if (is_null($cid)) {
            return json(['code' => 3, 'msg' => 'cid 丢失']);
        }

        // 实例化一个成果模型
        $achievement = new AchievementModel();
        // 通过cid获取中间表的一条数据
        $achievement_classify_table_info = $achievement->get_achievement_classify_table_info_by_cid($cid);

        // 获取中间表的数据，names
        // 数据对比，判断模板是不是网站上的
        // 获取excel第一行的表头数据
        $n = 1;
        foreach ($achievement_classify_table_info['table_content']['names'] as $row) {
            // 第一列的所有名称
            $name = $worksheet->getCellByColumnAndRow($n, 1)->getValue();
            if ($row != $name) {
                // 表头数据对比中间表数据，一致则认为是模板表s
                return json(['code' => 4, 'msg' => '模板不一致']);
            }
            $n++;
        }

        // 中间表ID
        $ct_id = $achievement_classify_table_info['id'];
        // 用户ID
        $uid = session('index_login')->id;
        // 创建时间
        $create_time = time();


        // 列的长度
        $cols_len = count($achievement_classify_table_info['table_content']['cols']);
        // 获取分类中间表的数值类型
        $classify_type_list = config('ams_config.classify_type_list');

        // 模板一致，开始获取文件中的数据
        for ($row = 2; $row <= $highestRow; ++$row) {
            // 列的分类
            // 获取中间的保存的生成表的列名 cols
            for ($i = 0; $i < $cols_len; $i++) {
                // 获取数据
                $var_row = $worksheet->getCellByColumnAndRow($i + 1, $row)->getValue();
                // 开始格式化 
                if (is_object($var_row))  $var_row = $var_row->__toString();
                // 分类中间表的数值类型判断
                foreach ($classify_type_list as $classify_type_list_row) {
                    $select_number = $achievement_classify_table_info['table_content']['selects'][$i];
                    if (($classify_type_list_row['value'] == $select_number)
                        && $classify_type_list_row['name'] == '时间'
                    ) {
                        $var_row = excelTime($worksheet->getCellByColumnAndRow($i + 1, $row)->getValue());
                        $var_row = strtotime($var_row);
                    } else if (($classify_type_list_row['value'] == $select_number)
                        && $classify_type_list_row['name'] == '数值'
                    ) {
                        $var_row = floatval($var_row) * 100;
                    }
                }

                // 按照正常的顺序，生成数据组
                $data[$achievement_classify_table_info['table_content']['cols'][$i]] = $var_row;
            }

            $data['pid'] = $ct_id;
            $data['uid'] = $uid;
            $data['status'] = 0;
            $data['create_time'] = $create_time;

            // 进行保存
            $save_res = $achievement->set_achievement_info_by_data($achievement_classify_table_info['table_name'], $data);

            if (!$save_res) {
                $erroe_data[] = $row;
            }
        }

        if (!empty($erroe_data)) {
            return json(['code' => 5, 'msg' => '异常数据，请检查文件', 'data' => $erroe_data]);
        }

        // 获取excel表的数据
        return json(['code' => 0, 'msg' => '批量上传完成']);
    }

    // 编辑成果
    public function edit()
    {
        if (request()->post()) {
            $datas = input('post.data');

            // 数据类型下拉列表数据
            $classify_type_list = config('ams_config.classify_type_list');
            $data = [];
            foreach ($datas as $row) {
                if ($row['value'] == '') {
                    return json(['code' => 1, 'msg' => '数据不能为空']);
                }

                if ('数值' == $classify_type_list[$row['selects'] - 1]['name']) {
                    $data[$row['key']] =  floatval($row['value']) * 100;
                } else if ('时间' == $classify_type_list[$row['selects'] - 1]['name']) {
                    $data[$row['key']] =  strtotime($row['value']);
                } else {
                    $data[$row['key']] = $row['value'];
                }
            }

            $pid = input('post.pid/d', null);
            if (!$pid) {
                return json(['code' => 2, 'msg' => '缺少 pid']);
            }
            $id = input('post.id/d', null);
            if (!$id) {
                return json(['code' => 3, 'msg' => '缺少 id']);
            }

            // 实例化一个成果模型
            $achievement = new AchievementModel();
            // 获取中间表的内容
            $classify_table_info = $achievement->get_achievement_classify_table_info_by_id($pid);
            // 获取分类表的数据
            $classify_info = $achievement->get_classify_info_by_id($classify_table_info['cid']);
            if ($classify_info['issue'] == 0) {
                return json(['code' => 4, 'msg' => '当前没有启用该分类，不能做任何修改']);
            }

            // 获取一条成果数据
            $achievement_info = $achievement->get_achievement_info_by_id($classify_table_info['table_name'], $id);

            // 0 编辑中 3 已驳回
            // if ($achievement_info['status'] == 4 || $achievement_info['status'] == 2) {
            //     return json(['code' => 0, 'msg' => '审核已通过，无需再次提交']);
            // }

            if ($achievement_info['status'] == 1) {
                return json(['code' => 3, 'msg' => '审核已提交，无需再次提交']);
            }

            $data['id'] = input('post.id/d', null);

            $res = $achievement->set_achievement_info_by_data($classify_table_info['table_name'], $data);
            if (!$res) {
                return json(['code' => 4, 'msg' => '修改失败，数据没做修改']);
            }

            // 编辑完成以后进入提交状态
            $achievement_res = $achievement->set_achievement_info($classify_table_info['table_name'], $id, ['status' => 0]);
            if (!$achievement_res) {
                return json(['code' => 4, 'msg' => '状态修改失败，请联系管理员']);
            }

            return json(['code' => 0, 'msg' => '修改成功']);
        }


        $pid = input('get.pid/d', null);
        $id = input('get.id/d', null);
        if (is_null($pid) || is_null($id)) {
            return redirect_index('ID 丢失', url('Achievement/index') . "?uid=" . session("index_login")->id);
        }
        // 实例化一个成果模型
        $achievement = new AchievementModel();
        // 获取中间表的内容
        $classify_table_info = $achievement->get_achievement_classify_table_info_by_id($pid);
        $cid = $classify_table_info['cid'];
        // 数据类型下拉列表数据
        $classify_type_list = config('ams_config.classify_type_list');
        // 获取成果的该条数据
        $achievement_info = $achievement->get_achievement_info_by_id($classify_table_info['table_name'], $id);

        if (!is_null($achievement_info['audit_id'])) {
            $aid = $achievement_info['audit_id'];
            $user = new UserModel();
            $user_info = $user->get_user_info_by_id($aid);
            $achievement_info['audit_name'] = $user_info['name'];
        }

        return view('edit', [
            'classify_table_info' => $classify_table_info,
            'classify_type_list' => $classify_type_list,
            'achievement_info' => $achievement_info,
            'pid' => $pid,
            'id' => $id,
            'cid' => $cid,
        ]);
    }

    // 删除成果
    public function del()
    {
        if (request()->post()) {
            $pid = input('post.pid/d', null);
            $id = input('post.id/d', null);

            if (is_null($pid) || is_null($id)) {
                return json(['code' => 1, 'msg' => '参数错误']);
            }

            // 实例化一个成果模型
            $achievement = new AchievementModel();
            // 获取中间表的内容
            $classify_table_info = $achievement->get_achievement_classify_table_info_by_id($pid);
            // 获取分类表的数据
            $classify_info = $achievement->get_classify_info_by_id($classify_table_info['cid']);
            if ($classify_info['issue'] == 0) {
                return json(['code' => 2, 'msg' => '当前没有启用该分类，禁止删除']);
            }

            // 获取一条成果数据
            $achievement_info = $achievement->get_achievement_info_by_id($classify_table_info['table_name'], $id);

            // 判断什么状态下可以删除
            // 0 编辑中 3 已驳回 可以删除
            if ($achievement_info['status'] == 4 || $achievement_info['status'] == 2) {
                return json(['code' => 3, 'msg' => '审核已通过，无发删除']);
            }

            if ($achievement_info['status'] == 1) {
                return json(['code' => 4, 'msg' => '审核已提交，无发删除']);
            }

            $achievement_del_res = $achievement->del_achievement_info($pid, $id);
            if (!$achievement_del_res) {
                return json(['code' => 5, 'msg' => '删除失败']);
            }
            return json(['code' => 0, 'msg' => '删除完成']);
        }
        return json(['code' => 99, 'msg' => '错误的请求方式']);
    }

    // 提交成果到审核
    public function audit()
    {
        if (request()->post()) {
            $pid = input('post.pid/d', null);
            $id = input('post.id/d', null);

            if (is_null($pid) || is_null($id)) {
                return json(['code' => 1, 'msg' => '参数错误']);
            }
            // 实例化一个成果模型
            $achievement = new AchievementModel();
            $classify_table_info = $achievement->get_achievement_classify_table_info_by_id($pid);
            // 获取分类表的数据
            $classify_info = $achievement->get_classify_info_by_id($classify_table_info['cid']);
            if ($classify_info['issue'] == 0) {
                return json(['code' => 2, 'msg' => '当前没有启用该分类，禁止提交审核']);
            }

            // 获取一条成果数据
            $achievement_info = $achievement->get_achievement_info_by_id($classify_table_info['table_name'], $id);

            // 判断什么状态下可以进行成果的审核提交
            // 0 编辑中 3 已驳回 4 已通过 可以提交
            if ($achievement_info['status'] == 4) {
                return json(['code' => 0, 'msg' => '审核已通过，无需再次提交']);
            }

            if ($achievement_info['status'] == 1) {
                return json(['code' => 3, 'msg' => '审核已提交，无需再次提交']);
            }

            $achievement_res = $achievement->set_achievement_info($classify_table_info['table_name'], $id, ['status' => 1]);
            if (!$achievement_res) {
                return json(['code' => 4, 'msg' => '未进入审核，请联系管理员']);
            }

            return json(['code' => 0, 'msg' => '进入审核']);
        }
    }

    // 自定义导出
    public function custom_import()
    {
        $cid = input('get.cid/d', null);
        if (is_null($cid)) {
            return redirect_index('ID 丢失', url('Achievement/index') . "?uid=" . session("index_login")->id);
        }
        $uid = session('index_login')->id;

        // 成果实例
        $achievement = new AchievementModel();
        // 获取中间表的内容
        $classify_table_info = $achievement->get_achievement_classify_table_info_by_cid($cid);
        // 用来获取表名
        $achievement_classify_table_info = $achievement->get_achievement_classify_table_info_by_cid($cid);
        // 数据类型下拉列表数据
        $classify_type_list = config('ams_config.classify_type_list');
        // 表名
        $table_name = $achievement_classify_table_info['table_name'];
        // 表内个人的所有数据
        $achievement_classify_table_other_info = $achievement->get_achievement_classify_table_other_info_by_tableName_and_uid($table_name, $uid);


        return view('custom_import', [
            'cid' => $cid,
            'classify_type_list' => $classify_type_list,
            'classify_table_info' => $classify_table_info,
            'achievement_classify_table_other_info' => $achievement_classify_table_other_info,
        ]);
    }

    // 成果导出
    public function import_excel()
    {
        $cid = input('post.cid/d', null);
        if (is_null($cid)) {
            return json(['code' => 1, 'msg' => '参数丢失']);
        }

        $uid = session('index_login')->id;

        // 根据状态下载所需要的的信息
        /**
         * -1 下载全部
         * 0  下载已通过
         * 1  自定义下载
         */
        $status = input('post.status/d', -1);


        $excel = new ExcelModel();
        $achievement = new AchievementModel();
        // 获取分类数据
        $classify_info = $achievement->get_classify_info_by_id($cid);
        // 需要保存的文件名
        $file_name = $classify_info['name'];
        // 表名 表内列的内容
        $achievement_classify_table_info = $achievement->get_achievement_classify_table_info_by_cid($cid);
        $table_name = $achievement_classify_table_info['table_name'];
        $table_content = $achievement_classify_table_info['table_content'];
        // 表格配置
        $excel_template_config =  config('ams_config.excel_template');

        // 第一种模式  全部下载
        if ($status == -1) {
            // 查询成果收集表中的所有数据
            $achievement_classify_table_other_info = $achievement->get_achievement_classify_table_other_info_by_tableName_and_uid($table_name, $uid);
            $data = $achievement_classify_table_other_info->toArray();
        }
        // 第二种模式  已通过
        else if ($status == 0) {
            // 查询成果收集表中的已通过数据
            $achievement_classify_table_other_info = $achievement->get_achievement_classify_table_other_info_by_tableName_and_uid_and_status($table_name, $uid, 4);
            $data = $achievement_classify_table_other_info->toArray();
        }
        // 第二种模式  自定义模式
        else if ($status == 1) {
            // 1 自定义下载的对应ID组
            $ids = input('post.ids/s', null);
            if (!$ids) {
                return json(['code' => 2, 'msg' => '请至少选择一条数据']);
            }

            $ids = explode(",", $ids);
            // 获取所有的数据
            $achievement_classify_table_other_info = $achievement->get_achievement_classify_table_other_info_by_tableName_and_uid($table_name, $uid);

            $data = [];
            foreach ($ids as $row_id) {
                foreach ($achievement_classify_table_other_info as $row) {
                    if ($row['id'] == $row_id) {
                        $data[] = $row;
                        break;
                    }
                }
            }
        } else {
            return json(['code' => 99, 'msg' => '模式错误']);
        }

        // 验证是否有数据
        if (!$achievement_classify_table_other_info || count($achievement_classify_table_other_info) <= 0) {
            return json(['code' => 2, 'msg' => '当前成果没有数据，无法下载']);
        }
        // 生成导出文件
        $res = $excel->excel_import($uid, $file_name, $table_content, $data);

        if ($res['code'] != 0) {
            return json(['code' => 3, 'msg' => $res['msg']]);
        }
        // 获取下载地址
        $download_url = $excel_template_config['import_path_download'] . '/' . $res['msg'];

        if (!is_file(config('ams_config.app_path') . '/public' . $download_url)) {
            return json(['code' => 4, 'msg' => '成果数据表格创建失败，请联系管理员']);
        }

        return json(['code' => 0, 'msg' => '开始下载', 'url' => $download_url]);
    }
}
